<template>
  <BaseDialog
    v-model:visible="visible"
    title="忘记密码"
    icon="Lock"
    width="500px"
    :show-footer="false"
    :close-on-click-modal="false"
    @close="resetAllForms"
  >
    <div class="forgot-password-form">
      <!-- 步骤指示器 -->
      <el-steps :active="currentStep" align-center class="steps">
        <el-step title="验证邮箱" />
        <el-step title="重置密码" />
        <el-step title="完成" />
      </el-steps>

      <!-- 第一步：输入邮箱 -->
      <div v-if="currentStep === 0" class="step-content">
        <div class="step-description">
          <el-text type="info">
            请输入您的注册邮箱，我们将向您发送密码重置链接
          </el-text>
        </div>
        
        <el-form
          ref="emailFormRef"
          :model="emailForm"
          :rules="emailRules"
          label-width="80px"
          @submit.prevent="handleSendResetEmail"
        >
          <el-form-item label="邮箱" prop="email">
            <BaseInput
              v-model="emailForm.email"
              type="email"
              placeholder="请输入您的注册邮箱"
              prefix-icon="Message"
              size="large"
              clearable
            />
          </el-form-item>
        </el-form>

        <div class="form-actions">
          <BaseButton
            variant="outline"
            size="large"
            @click="visible = false"
          >
            取消
          </BaseButton>
          <BaseButton
            type="primary"
            size="large"
            :loading="loading"
            @click="handleSendResetEmail"
          >
            发送重置邮件
          </BaseButton>
        </div>
      </div>

      <!-- 第二步：输入重置令牌和新密码 -->
      <div v-if="currentStep === 1" class="step-content">
        <div class="step-description">
          <el-text type="info">
            请查收邮件中的重置链接，或手动输入重置令牌和新密码
          </el-text>
        </div>
        
        <el-form
          ref="resetFormRef"
          :model="resetPasswordForm"
          :rules="resetRules"
          label-width="100px"
          @submit.prevent="handleResetPassword"
        >
          <el-form-item label="重置令牌" prop="token">
            <BaseInput
              v-model="resetPasswordForm.token"
              placeholder="请输入邮件中的重置令牌"
              prefix-icon="Key"
              size="large"
              clearable
            />
            <div class="form-tip">
              <el-text type="info" size="small">
                请从邮件中复制完整的重置令牌
              </el-text>
            </div>
          </el-form-item>

          <el-form-item label="新密码" prop="newPassword">
            <BaseInput
              v-model="resetPasswordForm.newPassword"
              type="password"
              placeholder="请输入新密码"
              prefix-icon="Lock"
              size="large"
              show-password
            />
            <div class="password-tips">
              <el-text type="info" size="small">
                密码长度6-20位，必须包含大小写字母和数字
              </el-text>
            </div>
          </el-form-item>

          <el-form-item label="确认密码" prop="confirmPassword">
            <BaseInput
              v-model="resetPasswordForm.confirmPassword"
              type="password"
              placeholder="请再次输入新密码"
              prefix-icon="Lock"
              size="large"
              show-password
            />
          </el-form-item>
        </el-form>

        <div class="form-actions">
          <BaseButton
            variant="outline"
            size="large"
            @click="currentStep = 0"
          >
            上一步
          </BaseButton>
          <BaseButton
            type="primary"
            size="large"
            :loading="loading"
            @click="handleResetPassword"
          >
            重置密码
          </BaseButton>
        </div>
      </div>

      <!-- 第三步：完成 -->
      <div v-if="currentStep === 2" class="step-content">
        <div class="success-content">
          <el-result
            icon="success"
            title="密码重置成功"
            sub-title="您的密码已经重置成功，请使用新密码登录"
          >
            <template #extra>
              <BaseButton
                type="primary"
                size="large"
                @click="handleComplete"
              >
                立即登录
              </BaseButton>
            </template>
          </el-result>
        </div>
      </div>

      <!-- 邮件发送成功提示 -->
      <div v-if="showEmailSent" class="email-sent-tip">
        <el-alert
          type="success"
          :closable="false"
          show-icon
        >
          <template #title>
            <div class="alert-content">
              <div class="alert-title">邮件已发送</div>
              <div class="alert-description">
                我们已向您的邮箱发送了密码重置邮件，请查收并按照邮件中的说明重置密码。
              </div>
              <div class="alert-actions">
                <el-button type="text" size="small" @click="currentStep = 1">
                  手动输入重置令牌
                </el-button>
                <el-button type="text" size="small" @click="handleResendEmail">
                  重新发送邮件
                </el-button>
              </div>
            </div>
          </template>
        </el-alert>
      </div>
    </div>
  </BaseDialog>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Message, Key, Lock } from '@element-plus/icons-vue'
import BaseDialog from '../common/BaseDialog.vue'
import BaseInput from '../common/BaseInput.vue'
import BaseButton from '../common/BaseButton.vue'
import axios from 'axios'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'success', 'login'])

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 表单引用
const emailFormRef = ref()
const resetFormRef = ref()

// 状态管理
const loading = ref(false)
const currentStep = ref(0)
const showEmailSent = ref(false)

// 邮箱表单
const emailForm = reactive({
  email: ''
})

// 重置密码表单
const resetPasswordForm = reactive({
  token: '',
  newPassword: '',
  confirmPassword: ''
})

// 验证规则
const emailRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ]
}

const resetRules = {
  token: [
    { required: true, message: '请输入重置令牌', trigger: 'blur' },
    { min: 32, message: '重置令牌长度不正确', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
    { 
      pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d@$!%*?&]{6,}$/, 
      message: '密码必须包含大小写字母和数字', 
      trigger: 'blur' 
    }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== resetPasswordForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 发送重置邮件
const handleSendResetEmail = async () => {
  if (!emailFormRef.value) return

  try {
    await emailFormRef.value.validate()
    loading.value = true

    const response = await axios.post('/auth/forgot-password', {
      email: emailForm.email
    })

    if (response.data.code === 200) {
      ElMessage.success('重置邮件已发送，请查收邮箱')
      showEmailSent.value = true
      // 不自动跳转到下一步，让用户选择
    } else {
      throw new Error(response.data.message || '发送失败')
    }
  } catch (error) {
    console.error('发送重置邮件失败:', error)
    ElMessage.error('发送失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 重新发送邮件
const handleResendEmail = async () => {
  showEmailSent.value = false
  await handleSendResetEmail()
}

// 重置密码
const handleResetPassword = async () => {
  if (!resetFormRef.value) return

  try {
    await resetFormRef.value.validate()
    loading.value = true

    const response = await axios.post('/auth/reset-password', {
      token: resetPasswordForm.token,
      newPassword: resetPasswordForm.newPassword,
      confirmPassword: resetPasswordForm.confirmPassword
    })

    if (response.data.code === 200) {
      ElMessage.success('密码重置成功')
      currentStep.value = 2
    } else {
      throw new Error(response.data.message || '重置失败')
    }
  } catch (error) {
    console.error('重置密码失败:', error)
    ElMessage.error('重置失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 完成重置，跳转到登录
const handleComplete = () => {
  visible.value = false
  emit('login')
}

// 重置表单
const resetAllForms = () => {
  if (emailFormRef.value) {
    emailFormRef.value.resetFields()
  }
  if (resetFormRef.value) {
    resetFormRef.value.resetFields()
  }
  
  Object.assign(emailForm, {
    email: ''
  })
  
  Object.assign(resetPasswordForm, {
    token: '',
    newPassword: '',
    confirmPassword: ''
  })
  
  currentStep.value = 0
  showEmailSent.value = false
}
</script>

<style scoped>
.forgot-password-form {
  padding: 0;
}

.steps {
  margin-bottom: var(--spacing-xl);
}

.step-content {
  min-height: 300px;
}

.step-description {
  margin-bottom: var(--spacing-lg);
  text-align: center;
  padding: var(--spacing-md);
  background-color: var(--color-info-light-9);
  border-radius: var(--border-radius-base);
}

.form-actions {
  display: flex;
  gap: var(--spacing-md);
  justify-content: flex-end;
  margin-top: var(--spacing-xl);
}

.form-tip,
.password-tips {
  margin-top: var(--spacing-xs);
}

.email-sent-tip {
  margin-top: var(--spacing-lg);
}

.alert-content {
  text-align: left;
}

.alert-title {
  font-weight: var(--font-weight-medium);
  margin-bottom: var(--spacing-sm);
}

.alert-description {
  margin-bottom: var(--spacing-md);
  color: var(--color-text-secondary);
  line-height: 1.6;
}

.alert-actions {
  display: flex;
  gap: var(--spacing-md);
}

.success-content {
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .form-actions {
    flex-direction: column;
  }
  
  .alert-actions {
    flex-direction: column;
    gap: var(--spacing-sm);
  }
}
</style>
